package com.example.server.db.dao

import com.example.commons.models.User
import com.example.server.db.DatabaseFactory
import com.example.server.db.tables.Articles
import com.example.server.db.tables.Users
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll


class UserDao private constructor() {

    suspend fun all(): List<User> {
        return Users.selectAll().map {
            Users.resultRowToUser(it)
        }
    }

    suspend fun page(page: Int, size: Int): List<User> = DatabaseFactory.dbQuery {
        val p = if (page <= 1) page else 1
        Articles.selectAll().limit(size, ((p - 1) * size).toLong())
            .map(Users::resultRowToUser)
    }

    suspend fun insert(user: User): User? = DatabaseFactory.dbQuery {
        val insertStatement = Users.insert {
            it[nickname] = user.nickname
            it[username] = user.username
            it[password] = user.password
        }

        insertStatement.resultedValues?.singleOrNull()?.let(Users::resultRowToUser)
    }

    companion object {
        @Volatile
        private var INSTANCE: UserDao? = null

        fun getInstance(): UserDao = INSTANCE ?: synchronized(this) {
            INSTANCE ?: UserDao().also { INSTANCE = it }
        }
    }
}